/**
 * 上传
 * @author xiaoqiang <465633678@qq.com>
 * @created 2018/11/02 09:45:25
 */
const path = require('path')
const Busboy = require('busboy')
const utils = require('./index')
const fs = require('fs')

function uploadFile(ctx, options) {
  const req = ctx.req
  /**
   * 获取文件类型
   * 用于区分存放目录
   */
  let fileType = options.fileType || 'common'
  // 获取目录绝对路径
  const filePath = path.join(options.path, fileType)
  /**
   * 是否有此目录
   * 则创建目录
   */
  const dirResult = utils.mkdirSync(filePath)
  return new Promise((rs, rj) => {
    try {
      // 实例化busboy
      const busboy = new Busboy({ headers: req.headers })
      console.log('文件上传中....')
      /**
       * 返回结构
       */
      let result = { 
        success: false,
        formData: {},
      }
      // 监听文件流
      busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
        console.log(`上传文件 - fieldname:${fieldname} - filename：${filename} - encoding: ${encoding}`)
        // 上传后的文件名
        filename = Math.random().toString(16).slice(2) + utils.getExtName(filename)
        // 保存的文件绝对路径
        const saveTo = path.join(filePath, filename)
        // pipe
        file.pipe(fs.createWriteStream(saveTo))
        // 监听end事件
        file.on('end', () => {
          // 修改状态为true
          result.success = true
          result.message = '上传成功'
          // 将文件名返回
          result.formData.imageName = filename
          console.log('上传文件成功')
          rs(result)
        })
      })
      /**
       * 监听字段
       */
      busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => {
        console.log(`字段 - fieldname: ${fieldname} - val: ${val} - fieldnameTruncated: ${fieldnameTruncated} - valTruncated: ${valTruncated} - encoding: ${encoding} - mimetype: ${mimetype}`)
        result.formData[fieldname] = inspect(val);
      })
      /**
       * 监听finish
       */
      busboy.on('finish', () => {
        console.log('完成')
        rs(result)
      })
      /**
       * 监听错误事件
       */
      busboy.on('error', () => {
        console.log('出现错误')
        rj(result)
      })
      req.pipe(busboy)
    } catch (e) {
      result.message = '上传失败'
      result.success = false
      rj(result)
    }
  })
}

// 导出模块
module.exports = uploadFile